package personnel.department.pages.widgets;

import java.lang.reflect.Field;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class NumberWidget extends AbstractWidget<Integer> {

	private String title;
	private Composite parent;
	private Label label;
	private Text text;

	public NumberWidget(Composite parent, String title, Field field) {
		super(field);
		this.parent = parent;
		this.title = title;
		create();
	}

	@Override
	protected void create() {
		label = new Label(parent, SWT.NONE);
		label.setText(title);
		text = new Text(parent, SWT.BORDER);
		
		//for a test
//		text.setText("1");
		
		text.setLayoutData(new GridData(150, 15));
		text.addVerifyListener(getVerifyNumberListener());
		text.addListener(SWT.Modify, event -> modify());
		super.create();
	}

	private VerifyListener getVerifyNumberListener() {
		return event -> {  
			switch (event.keyCode) {  
			case SWT.BS:           // Backspace  
			case SWT.DEL:          // Delete  
			case SWT.HOME:         // Home  
			case SWT.END:          // End  
			case SWT.ARROW_LEFT:   // Left arrow  
			case SWT.ARROW_RIGHT:  // Right arrow 
			case 0:
				return;  
			}  

			if (!Character.isDigit(event.character)) {  
				event.doit = false;  // disallow the action  
			}  
		};
	}
	
	@Override
	public void setValue(Integer value) {
		text.setText(value == null ? "" : String.valueOf(value));
		modify();
	}
	
	@Override
	public Integer getValue() {
		return text.getText().isEmpty() ? null : Integer.parseInt(text.getText());
	}

	@Override
	protected Control getWidget() {
		return text;
	}

}
